package com.linck.im.server.handler;

import com.linck.im.model.constant.Msg;
import com.linck.im.model.proto.ProtoMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 连续三次心跳检测失败，关闭连接
 *
 * @author: linck
 * @create: 2021-01-28
 */
@Slf4j
public class ServeHeartBeatHandler extends SimpleChannelInboundHandler<ProtoMsg.HeartBeat> {

    int readIdleTimes = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ProtoMsg.HeartBeat heartBeat) throws Exception {
        readIdleTimes = 0;
        log.debug("{} 心跳检测正常", ctx.channel().remoteAddress());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;

        String eventType = null;
        switch (event.state()) {
            case READER_IDLE:
                eventType = "读空闲";
                readIdleTimes++; // 读空闲的计数加1
                break;
            case WRITER_IDLE:
                eventType = "写空闲";
                // 不处理
                break;
            case ALL_IDLE:
                eventType = "读写空闲";
                // 不处理
                break;
        }
        log.warn("{}\t超时事件：{}\t", ctx.channel().remoteAddress(), eventType);
        if (readIdleTimes > 3) {
            log.warn(" {} 读空闲连续超过3次，关闭连接", ctx.channel().remoteAddress());
            ctx.channel().writeAndFlush(Msg.HEART_OVER_TIME);
            ctx.channel().close();
        }
    }
}
